package ru.weho.osmwidget;

import ru.weho.osmwidget.R;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;

public class OSMWidgetProvider extends AppWidgetProvider {
	@SuppressWarnings("unused")
	private static final String TAG = "OSMWidgetProvider";

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		Intent serviceIntent = new Intent(context, OSMUpdateService.class);
		context.startService(serviceIntent);
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		SharedPreferences.Editor prefs = context.getSharedPreferences(OSMWidgetConfigure.PREFS_NAME, 0).edit();
		for (int widgetId : appWidgetIds) {
			prefs.remove(OSMWidgetConfigure.MAPTYPE_KEY + widgetId);
			prefs.remove(OSMWidgetConfigure.ZOOM_KEY + widgetId);
			
		}
		super.onDeleted(context, appWidgetIds);

		ComponentName provider = new ComponentName(context, OSMWidgetProvider.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(context);
		if (manager.getAppWidgetIds(provider).length == 0) {
			// Stop service if there are no more widgets on screen
			Intent serviceIntent = new Intent(context, OSMUpdateService.class);
			context.stopService(serviceIntent);
		}
	}

	static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
		RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
		appWidgetManager.updateAppWidget(appWidgetId, views);
	}
}
